<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Game extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
    {

        parent::__construct();

        $this->load->model('game_model');
    }

  // 	public function set_battle($id1, $id2){
		// unset_waiting($id1);
		// unset_waiting($id2);
		// //start battle
  //   }

    public function get_all_waiting(){
    	$files = get_filenames($this->config->item('dir_game'));
        $filtered_files = array();
    	// $filtered_files = array(
    	// 	'waiting'	=>	array(),
    	// 	'challenges'	=> array()
    	// 	);
    	foreach ($files as $file) {
    		if(strpos($file, $this->config->item('postfix')['waiting'].$this->config->item('ext_json'))){
    			$file_contents = json_decode(read_file($this->config->item('dir_game').$file));
    			if($file_contents->{'id'} != $this->session->userdata('id')){
    				array_push($filtered_files, $file_contents);
    			}
    		}
    		// else if(strpos(){
    		// 	array_push($filtered_files['challenges'], json_decode(read_file($this->config->item('dir_game').$file)));
    		// }
    	}
    	echo json_encode($filtered_files);
    }

    public function get_challenge(){
        try{
            echo read_file($this->config->item('dir_game').$this->session->userdata('id').$this->config->item('postfix')['challenge'].
                        $this->config->item('ext_json'));
        } catch(Exception $ex){
            echo json_encode('');
        }
    }

    /**
    * @return 1: accepted, 0: denied, -1: no answer
    */
    public function get_challenge_accepted($player_challenged_id){
        if(read_file($this->config->item('dir_game').$this->session->userdata('id').'-'.$player_challenged_id.
            $this->config->item('postfix')['battle'].
            $this->config->item('ext_json')) != ''){
            echo 1;
        }
        else if(read_file($this->config->item('dir_game').$this->session->userdata('id').
                $this->config->item('postfix')['waiting'].
                $this->config->item('ext_json')) != ''){
            echo 0;
        }
        else{
            echo -1;
        }
    }

    public function set_challenge($id){
        $file = $this->config->item('dir_game').$id.$this->config->item('postfix')['challenge'].$this->config->item('ext_json');
        if(!read_file($file)){
            if(write_file($file, json_encode(array(
                'id'    =>  $this->session->userdata('id'),
                'player_name'   =>  $this->session->userdata('player_name')
            )))){
                echo json_encode(TRUE);
            }
            else{
                echo json_encode(FALSE);
            }

        }
        else{
            echo json_encode(FALSE);
        }
    }

    public function unset_challenge(){
        $file = $this->config->item('dir_game').$this->session->userdata('id').$this->config->item('postfix')['challenge'].$this->config->item('ext_json');
        try{
            $file_contents = json_decode(read_file($file));
            $this->set_waiting(
                array(
                    'id'  =>  $this->session->userdata('id'),
                    'player_name'   =>  $this->session->userdata('player_name')
                    ),
                array(
                    'id'    =>  $file_contents->{'id'},
                    'player_name'   =>     $file_contents->{'player_name'}
                    )
                );
            unlink($file);
            echo json_encode(TRUE);
        } catch(Exception $ex){
            echo json_encode(FALSE);
        }
    }

    public function unset_waiting($id1, $id2){
        try{
            unlink($this->config->item('dir_game').$id1.$this->config->item('postfix')['waiting'].$this->config->item('ext_json'));
            unlink($this->config->item('dir_game').$id2.$this->config->item('postfix')['waiting'].$this->config->item('ext_json'));
            echo json_encode(TRUE);
        } catch(Exception $ex){
            echo json_encode(FALSE);
        }
    }

    public function set_waiting($data1, $data2){
        // var_dump($this->config->item('dir_game').$id.$this->config->item('postfix')['waiting'].$this->config->item('ext_json')); exit();
        write_file($this->config->item('dir_game').$data1['id'].$this->config->item('postfix')['waiting'].$this->config->item('ext_json'),
            json_encode(array(
                'id'    =>  $data1['id'],
                'player_name'   =>  $data1['player_name']
            )));
        write_file($this->config->item('dir_game').$data2['id'].$this->config->item('postfix')['waiting'].$this->config->item('ext_json'),
            json_encode(array(
                'id'    =>  $data2['id'],
                'player_name'   =>  $data2['player_name']
            )));
    }

    /**
    * Start Battle from here...
    */
    public function index(){
        if(!$this->session->userdata('id')){
            redirect('admin/index', 'refresh');
        }
        else{
             $this->load->view('include/template', array(
                'content'   =>  'game',
                'data'      =>  array(
                    'oponent_id'    =>  $this->session->flashdata('oponent_id'),
                    'oponent_name'  =>  $this->session->flashdata('oponent_name')
                    )
            ));
        }
    }

    public function start_battle($oponent_id, $oponent_name, $is_mechallenger){
        $this->session->set_userdata('oponent_id', $oponent_id);
        $this->session->set_userdata('oponent_name', $oponent_name);
        $this->session->set_userdata('is_mechallenger', $is_mechallenger);

        $oponent_rankData = $this->game_model->get_rank($oponent_id);

        $classData = $this->config->item('classes')[$oponent_rankData[0]['class']];
        $classDataSize = sizeof($classData);

        $rankIdx = floor($oponent_rankData[0]['wins'] / $this->config->item('wins_per_rank')) - 1;
        if($rankIdx < 0) $rankIdx = 0;
        else if($rankIdx >= $classDataSize) $rankIdx = $classDataSize;

        $this->session->set_userdata('oponent-class', $oponent_rankData[0]['class']);
        $this->session->set_userdata('oponent-rank', $classData['ranks'][$rankIdx]);

        redirect(base_url('index.php/game'), 'refresh');
    }

    public function get_cards($challenger_id){
        $file_contents;
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        $file = $this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
            $this->config->item('ext_json');
        if(($file_contents = json_decode(read_file($file))) == ''){
            $battlefile = $this->config->item('dir_game').$defender_id.$this->config->item('postfix')['challenge'].$this->config->item('ext_json');
            if(file_exists($battlefile)) unlink($battlefile);
            write_file($file, json_encode($file_contents = $this->generate_cards()));
        }
        else{
            write_file($file, '');
        }

        echo json_encode($file_contents);
    }

    public function surrender($challenger_id){
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        $file = $this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
            $this->config->item('ext_json');

        if(file_exists($file)) unlink($file);

        echo json_encode(TRUE);
    }

    public function is_battle_ended($challenger_id){
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        $file = $this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
            $this->config->item('ext_json');

        if(file_exists($file)) echo json_decode(0);
        else echo json_encode(1);
    }

    public function get_battle($challenger_id){
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        $file = $this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
                                $this->config->item('ext_json');
        try{
            $file_contents = read_file($file);
            /**
            * You have the right to delete since it is your oponent's data else not {"2":
            */
            if(strpos($file_contents, '{"'.$this->session->userdata("oponent_id").'":') === 0){
                write_file($file, '');
                echo $file_contents;
            }
            else{
                echo '';
            }
        } catch(Exception $ex){
            echo json_encode('');
        }
    }

    public function update_rank($player_id, $hasWon, $class=null){
        if($class != null){
            $this->session->set_userdata($class);
            $this->game_model->update_rank($player_id, $hasWon, $class);
        }
        else{
            $this->game_model->update_rank($player_id, $hasWon);
        }

        echo json_encode(1);
    }

    public function update_battle($challenger_id){
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        write_file($this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
                        $this->config->item('ext_json'), $this->input->post('data'));
        echo json_encode(TRUE);
    }

    public function is_oponent_ready($challenger_id){
        $defender_id = ($challenger_id == $this->session->userdata('id') ? $this->session->userdata('oponent_id') : $this->session->userdata('id'));
        if(read_file($this->config->item('dir_game').$challenger_id.'-'.$defender_id.$this->config->item('postfix')['battle'].
            $this->config->item('ext_json')) == ''){
            echo json_encode(TRUE);
        }
        else{
            echo json_encode(FALSE);
        }
    }

    public function generate_cards(){
        $master;
        return array(
            'master' =>  ($cards = $this->get_master()),
            'deck'  =>  $this->get_deck($cards)
            );
    }

    public function get_master(){
        $cards = array();
        $suites = array('Clubs', 'Diamonds', 'Hearts', 'Spades');
        $faces = array('Sixes', 'Sevens', 'Eigths', 'Nines', 'Tens', 'Jacks', 'Queens', 'Kings', 'Aces');
        foreach($suites as $suite){
            $facesPerSuite = array();
            for ($x = 0; $x < sizeof($faces); $x++) {
                $face = $faces[$x];
                array_push($facesPerSuite, array(
                    'face'      =>  $face,
                    'status'    =>  $this->config->item('card_status')['deck'],
                    'img'       =>  (strtoupper($face[0]) == 'J' || strtoupper($face[0]) == 'Q'
                        || strtoupper($face[0]) == 'K' || strtoupper($face[0]) == 'A'
                        ? strtoupper($face[0]) : ($x + 6)).strtoupper($suite[0])
                    ));
            }
            $cards[$suite] = $facesPerSuite;
        }
        return $cards;
    }

    public function get_deck($master){
        $deck = array();
        $x = 0;
        foreach ($master as $face) {
            foreach ($face as $card) {
                array_push($deck, $x++);
            }
        }

        shuffle($deck);

        return $deck;
    }
	
}

/* End of file game.php */
/* Location: ./application/controllers/game.php */